package server

import (
	"encoding/json"
	"net/http"
	"tikrok/internal/log"
)

type API struct {
	registry *TunnelRegistry
	addr     string
}

func NewAPI(registry *TunnelRegistry, addr string) *API {
	return &API{registry, addr}
}

func (a *API) Start() {
	mux := http.NewServeMux()
	mux.HandleFunc("/metrics", a.handleMetrics)
	mux.HandleFunc("/tunnels", a.handleTunnels)

	go func() {
		log.Info("Starting admin API on %s", a.addr)
		if err := http.ListenAndServe(a.addr, mux); err != nil {
			log.Error("API server failed: %v", err)
		}
	}()
}

func (a *API) handleMetrics(w http.ResponseWriter, r *http.Request) {
	// 返回系统指标数据
	json.NewEncoder(w).Encode(metrics)
}

func (a *API) handleTunnels(w http.ResponseWriter, r *http.Request) {
	a.registry.RLock()
	defer a.registry.RUnlock()

	tunnels := make([]map[string]interface{}, 0)
	for url, t := range a.registry.tunnels {
		tunnels = append(tunnels, map[string]interface{}{
			"url":      url,
			"client":   t.ctl.id,
			"protocol": t.req.Protocol,
			"created":  t.start,
		})
	}
	json.NewEncoder(w).Encode(tunnels)
}
